package toolkits;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * Move the files under data path to its directory respectively
 * the directory name is pciorderid.substring(0,length-3)
 * @author wei
 *
 */
public class ConvertEncryptedFilesDir {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws IOException {
		
		System.out.println("WARNING: All file will move to new directory, not copy");
		
		System.out.println("Plealse enter data path(Example: /app/xxx/pcidata/bge/20091217001/data)");
        String datapath = new BufferedReader(new InputStreamReader(System.in)).readLine();
        
		if(datapath!=null && !"".equals(datapath)){
			if(!datapath.endsWith(File.separator)){
				datapath+=File.separator;
			}
			
			File f=new File(datapath);
			if(f.isDirectory()){
				System.out.println("processing...");
				ConvertEncryptedFilesDir converter=new ConvertEncryptedFilesDir(); 
				converter.go(datapath);
				System.out.println("done");
			}else{
				System.out.println("Please enter valid path.");
			}
			
			
		}else{
			System.out.println("Please enter valid path.");
		}
		
		
	}
	
	private void debug(Object obj){
		if(false){
			System.out.println(obj.toString());
		}
	}
	
	
	public void go(String dataPath) {
		File dataFile = new File(dataPath);

		File[] files = dataFile.listFiles(new FileFilter() {

			public boolean accept(File f) {

				return f.isFile() && 
						(f.getName().endsWith(".aesEncrypted") || f.getName().endsWith(".rsaEncryptedAesKey"));
			}

		});
		debug(files.length);
		for(File f : files){
			try {
				copy(f,getNewFile(dataPath,f.getName()));
				f.delete();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	
	private File getNewFile(String dataPath,String fileName){
		int pos=fileName.indexOf(".");
		if(pos>3){
			String newPath=dataPath+fileName.substring(0,pos-3)+File.separator;
			
			File file=new File(newPath);
			if(!file.exists()){
				file.mkdirs();
			}
			
			return new File(newPath+fileName);
		}
		
		return null;
		
	}
	
	private void copy(File source,File target)throws FileNotFoundException,IOException{
		InputStream in=new FileInputStream(source);
		OutputStream out=new FileOutputStream(target);
		byte c[]=new byte[1];
		while(in.read(c) != -1){
			out.write(c);
		}
		
		in.close();
		out.flush();
		out.close();
	}

}
